package com.oe.gateway.filters;

import com.alibaba.fastjson.JSONObject;
import com.oe.common.build.ResponseBuilder;
import com.oe.common.resp.LdmResponse;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class IPLimitFilter implements GlobalFilter, Ordered {

        private int DEFAULT_RATE=100;

        private int DEFAULT_INTERNAL=60*1000;

        ConcurrentHashMap<String,IpItem> ipLimitMap=new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String hostName = request.getRemoteAddress().getHostName();
        IpItem item = ipLimitMap.get(hostName);
        if (item==null){
            //配置固定IP，一分钟内限制最多可以访问1000次
            ipLimitMap.putIfAbsent(hostName,new IpItem(DEFAULT_RATE,DEFAULT_INTERNAL));
            item=ipLimitMap.get(hostName);
        }
        if(item.isAllow()){
            return chain.filter(exchange);
        }else {
            response.setStatusCode(HttpStatus.SEE_OTHER);
            return response.writeWith((Publisher)Flux.just( this.getBodyBuffer(exchange.getResponse(), ResponseBuilder.buildResponse(false,"303","request too frequently！",null))));
        }

    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 封装返回值
     *
     * @param response
     * @param result
     * @return
     */
    private DataBuffer getBodyBuffer(ServerHttpResponse response, LdmResponse result) {
        return (DataBuffer) response.bufferFactory().wrap(JSONObject.toJSONBytes(result));
    }


    
}
